package com.aeromedia.testcustomapplication;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.aeromedia.vh_sdk.repository.Observable;
import com.aeromedia.vh_sdk.state.SystemData;
import com.aeromedia.vh_sdk.repository.RoomClientRepository;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Random;
import java.util.function.IntFunction;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.WindowDecorActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.widget.ToolbarWidgetWrapper;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class CustomServiceActivity extends AppCompatActivity {
    private static final int PERMISSION_REQ_ID = 123;
    private static final String TAG = "CustomServiceActivity";
    private static final String[] REQUESTED_PERMISSIONS = {Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CALL_LOG,
            Manifest.permission.ACCESS_FINE_LOCATION};
    AlertDialog dialog = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_service);
        actionBarChange();

        Log.d(TAG, "onCreate:"
                + " SystemData.userId:" + SystemData.userId
                + " SystemData.deviceId:" + SystemData.deviceId
                + " SystemData.roomId:" + SystemData.roomId);
        RoomClientRepository.INSTANCE.init(SystemData.userId, SystemData.deviceId, SystemData.roomId, SystemData.clientType);
        RoomClientRepository.INSTANCE.connect();
        Log.d(TAG, "onCreate: ");

        dialog = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请检查网络状态,重新连接网络")
                .setPositiveButton("确认",
                        (dialog1, which) -> {
                            RoomClientRepository.INSTANCE.disconnect();
                            RoomClientRepository.INSTANCE.connect();
                        }).setCancelable(false).create();
        RoomClientRepository.INSTANCE.register(dialogObservable);


        ArrayList<String> strings = new ArrayList<>();
        strings.stream().toArray(new IntFunction<String[]>() {
            @Override
            public String[] apply(int value) {
                return new String[value];
            }
        });

        checkPermissions();
    }

    @SuppressLint({"ResourceAsColor", "RestrictedApi"})
    private void actionBarChange() {
        if (getSupportActionBar() != null) {
//            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("客服列表");
            Class<? extends ActionBar> windowDecorActionBarClazz = (getSupportActionBar()).getClass();
            Field mDecorToolbar = null;
            try {
                mDecorToolbar = windowDecorActionBarClazz.getDeclaredField("mDecorToolbar");
                mDecorToolbar.setAccessible(true);
                ToolbarWidgetWrapper toolbarWidgetWrapper = (ToolbarWidgetWrapper) mDecorToolbar.get(((WindowDecorActionBar) getSupportActionBar()));
//                toolbarWidgetWrapper.setDefaultNavigationIcon(getResources().getDrawable(R.drawable.idle_state));
                toolbarWidgetWrapper.setNavigationIcon(getResources().getDrawable(R.drawable.custom_ic_ab_back_material));

                @SuppressLint("RestrictedApi") Toolbar toolbar = (Toolbar) toolbarWidgetWrapper.getViewGroup();
                toolbar.setTitleTextColor(R.color.black);
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
//            toolbar.setLogo(getResources().getDrawable(R.drawable.idle_state));
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            StatusBarUtils.setActivityTranslucent(this);
        }
    }

    Observable.Observer dialogObservable = new Observable.Observer() {
        @Override
        public void update(boolean it) {
            runOnUiThread(() -> {
                if (!it && !dialog.isShowing()) {
                    dialog.show();
                }
                if (it && dialog.isShowing()) {
                    dialog.dismiss();
                }
            });

        }
    };

    private void checkPermissions() {
        if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[3], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[4], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[5], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[6], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[7], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[8], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[9], PERMISSION_REQ_ID)
        ) {

        } else {
            finish();
        }
    }

    public boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    REQUESTED_PERMISSIONS,
                    requestCode);
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RoomClientRepository.INSTANCE.unregister(dialogObservable);
    }



}
